import React, {useState, useEffect} from 'react';
import {Table, Space, Button} from "antd";

import Detail from "./components/detail";
import Authz from "./components/authz";

import {UserApi} from '@api/index'

import './list.less'

export default () => {

    const [list, setList] = useState([])
    const [userCode, setUserCode] = useState()
    const [auth, setAuth] = useState()
    const [detail, setDetail] = useState()

    const [total, setTotal] = useState(0)
    const [pageSize, setPageSize] = useState(20)
    const [page, setPage] = useState(0)

    useEffect(() => {
        getUserList()
    }, [page, pageSize])

    const getUserList = async () => {
        let params = {
            page: page,
            pageSize: pageSize,
        }
        let ret = await UserApi.list(params);
        if (ret && ret.code === 200) {
            setList(ret.data.content || [])
            setTotal(ret.data.totalElements)
        }
    }

    const openAuth = (userCode) => {
        setAuth(true)
        setUserCode(userCode)
    }

    const closeAuth = () => {
        setAuth(false)
    }

    const handleDetail=(userCode)=>{
        setDetail(true)
        setUserCode(userCode)
    }

    const closeDetail = () => {
        setDetail(false)
    }

    const columns = [
        {
            title: '姓名',
            dataIndex: 'userName',
            key: 'userName',
            width: '20%',
            render: (text, record) => (<a onClick={() => handleDetail(record.userCode)}>{record.userName}</a>),
        },
        {
            title: '性别',
            dataIndex: 'sexName',
            key: 'sexName',
            width: '10%',
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '邮箱',
            dataIndex: 'mail',
            key: 'mail',
        },
        {
            title: '状态',
            dataIndex: 'stateName',
            key: 'stateName'
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 150,
            key: 'action',
            render: (text, record) => (
                <Space size="small">
                    <Button type="link" size="small">冻结</Button>
                    <Button type="link" size="small" onClick={() => openAuth(record.userCode)}>授权</Button>
                </Space>
            )
        },
    ];

    const pagination = {
        onChange: (page, pageSize) => {
            setPageSize(pageSize)
            setPage(page - 1)
        },
        pageSize: pageSize,
        total: total
    }


    return (
        <div>
            <Table columns={columns} dataSource={list} pagination={pagination}/>
            <Detail open={detail} userCode={userCode} close={closeDetail}/>
            <Authz open={auth} userCode={userCode} close={closeAuth}/>
        </div>
    );

}
